package com.codeerror.demo.adapter;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.codeerror.demo.R;
import com.codeerror.demo.ui.fragment.TodoBsdFragment;
import com.codeerror.demo.bean.AnniversaryBean;
import com.codeerror.demo.bean.CardBean;
import com.codeerror.demo.bean.CountDownBean;
import com.codeerror.demo.bean.PromiseBean;
import com.codeerror.demo.bean.TodoBean;
import com.codeerror.demo.bean.TodoListBean;
import com.codeerror.demo.util.DateUtil;

import java.util.List;

public class CardWrapperRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final Activity activity;
    private final List<CardBean> cardList;

    private OnClickAddTodoListener onClickAddTodoListener;

    public CardWrapperRecyclerAdapter(Activity activity, List<CardBean> cardList) {
        this.activity = activity;
        this.cardList = cardList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if (viewType == CardBean.CARD_TYPE.COUNT_DOWN.ordinal()) {
            // 倒计时卡片
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_recycler_card_count_down, parent, false);
            return new countDownHolder(view);
        } else if (viewType == CardBean.CARD_TYPE.PROMISE.ordinal()) {
            // 承诺卡片
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_recycler_card_promise, parent, false);
            return new promiseHolder(view);
        } else if (viewType == CardBean.CARD_TYPE.ANNIVERSARY.ordinal()) {
            // 纪念日卡片
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_recycler_card_anniversary, parent, false);
            return new anniversaryHolder(view);
        } else if (viewType == CardBean.CARD_TYPE.TODO_LIST.ordinal()) {
            // 待办集卡片
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_recycler_card_todo_list, parent, false);
            return new todoListHolder(view);
        }
        return null;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == CardBean.CARD_TYPE.COUNT_DOWN.ordinal()) {
            countDownHolder countHolder = (countDownHolder) holder;
            CountDownBean countDownBean = (CountDownBean) cardList.get(position);
            countHolder.title.setText("距离 " + countDownBean.getName() + " 还有");
            countHolder.leaveDays.setText(DateUtil.getDaysGap(countDownBean.getTime(), System.currentTimeMillis()) + "天");
        } else if (getItemViewType(position) == CardBean.CARD_TYPE.PROMISE.ordinal()) {
            promiseHolder mPromiseHolder = (promiseHolder) holder;
            PromiseBean promiseBean = (PromiseBean) cardList.get(position);
            mPromiseHolder.name.setText(promiseBean.getName());
        } else if (getItemViewType(position) == CardBean.CARD_TYPE.ANNIVERSARY.ordinal()) {
            anniversaryHolder mAnniversaryHolder = (anniversaryHolder) holder;
            AnniversaryBean anniversaryBean = (AnniversaryBean) cardList.get(position);
            mAnniversaryHolder.title.setText(anniversaryBean.getName());
            mAnniversaryHolder.time.setText(DateUtil.getFormattedTime(anniversaryBean.getTime()));
            mAnniversaryHolder.leaveTime.setText("距离 " + anniversaryBean.getName()
                    + " 还有" + getAnniversaryGapDays(anniversaryBean) + "天");
        } else if (getItemViewType(position) == CardBean.CARD_TYPE.TODO_LIST.ordinal()) {
            todoListHolder mTodoListHolder = (todoListHolder) holder;
            TodoListBean todoListBean = (TodoListBean) cardList.get(position);
            mTodoListHolder.title.setText(todoListBean.getName());
            mTodoListHolder.time.setText(DateUtil.getHourAndMinuteOfTime(todoListBean.getTime()) + " 开始");
            // 加载Todo时间线的LinearLayout
            updateTodoList(mTodoListHolder.ll, todoListBean.getTodoList());
            // 设置添加待办事件
            mTodoListHolder.addTodo.setOnClickListener(view -> {
                TodoBsdFragment bsdFragment = TodoBsdFragment.getInstance();
                bsdFragment.setOnCreateTodoListener(todoBean -> {
                    todoListBean.getTodoList().add(todoBean);
                    todoListBean.save();
                    updateTodoList(mTodoListHolder.ll, todoListBean.getTodoList());
                });
                onClickAddTodoListener.onClickAddTodo(bsdFragment, todoListBean.getTime());
            });
        }
    }

    /**
     * 更新TodoList中待办内容
     */
    @SuppressLint("SetTextI18n")
    private void updateTodoList(LinearLayout ll, List<TodoBean> todoBeanList){
        ll.removeAllViews();
        for (TodoBean todoBean : todoBeanList){
            View itemView = LayoutInflater.from(activity).inflate(R.layout.item_ll_time_line, ll, false);
            TextView title = itemView.findViewById(R.id.tv_todo_title);
            TextView time = itemView.findViewById(R.id.tv_todo_time);
            FrameLayout fl = itemView.findViewById(R.id.fl_todo_is_achieved);
            ImageView achieved = itemView.findViewById(R.id.iv_todo_achieved);
            View dot = itemView.findViewById(R.id.dot_time_line);
            // 设置标题
            title.setText(todoBean.getName());
            // 设置待办时间
            if (todoBean.getStartTime() != 0){
                if (todoBean.getEndTime()!=0){
                    time.setText(DateUtil.getHourAndMinuteOfTime(todoBean.getStartTime())
                            + " - " + DateUtil.getHourAndMinuteOfTime(todoBean.getEndTime()));
                }else {
                    time.setText(DateUtil.getHourAndMinuteOfTime(todoBean.getStartTime()));
                }
            }else {
                time.setVisibility(View.GONE);
            }
            // 设置待办是否已完成
            if (todoBean.getIsAchieved() == 1){
                // 已完成
                dot.setBackgroundResource(R.drawable.dot_time_line_achieved);
                title.setTextColor(Color.GRAY);
                time.setTextColor(Color.GRAY);
                achieved.setVisibility(View.VISIBLE);
            }else if (todoBean.getIsAchieved() == 0){
                // 未完成
                dot.setBackgroundResource(R.drawable.dot_time_line_not_achieved);
                title.setTextColor(Color.BLACK);
                time.setTextColor(Color.BLACK);
                achieved.setVisibility(View.GONE);
            }
            // 设置RadioButton点击事件
            fl.setOnClickListener(view -> {
                if (todoBean.getIsAchieved() == 1){
                    // 已完成，点击后未完成
                    dot.setBackgroundResource(R.drawable.dot_time_line_not_achieved);
                    title.setTextColor(Color.BLACK);
                    time.setTextColor(Color.BLACK);
                    todoBean.setIsAchieved(0);
                    showAchievedAnim(achieved, false);
                }else if (todoBean.getIsAchieved() == 0){
                    // 未完成，点击后完成
                    dot.setBackgroundResource(R.drawable.dot_time_line_achieved);
                    title.setTextColor(Color.GRAY);
                    time.setTextColor(Color.GRAY);
                    todoBean.setIsAchieved(1);
                    achieved.setVisibility(View.VISIBLE);
                    achieved.setScaleX(0); achieved.setScaleY(0);
                    showAchievedAnim(achieved, true);
                }
                todoBean.save();
            });
            ll.addView(itemView);
        }
        if (todoBeanList.size() > 0){
            ll.getChildAt(ll.getChildCount()-1).findViewById(R.id.bottom_dot).setVisibility(View.VISIBLE);
        }
    }

    /**
     * 开启完成待办的动画
     * @param iv
     */
    private void showAchievedAnim(ImageView iv, boolean isAchieved){
        ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
        anim.setDuration(200);
        anim.addUpdateListener(valueAnimator -> {
            float val = (float) valueAnimator.getAnimatedValue();
            if (isAchieved){
                iv.setScaleX(val);
                iv.setScaleY(val);
            }else {
                iv.setScaleX(1-val);
                iv.setScaleY(1-val);
                if (val == 1){
                    iv.setVisibility(View.GONE);
                }
            }
        });
        anim.start();
    }

    /**
     * 获得距离纪念日还剩几天
     *
     * @return
     */
    private int getAnniversaryGapDays(AnniversaryBean anniversaryBean) {
        if (DateUtil.getMonthOfTime(anniversaryBean.getTime()) >= DateUtil.getMonthOfTime(System.currentTimeMillis())) {
            return (DateUtil.getMonthOfTime(anniversaryBean.getTime()) -
                    DateUtil.getMonthOfTime(System.currentTimeMillis())) * 30
                    + DateUtil.getDayOfTime(anniversaryBean.getTime()) -
                    DateUtil.getDayOfTime(System.currentTimeMillis());
        } else {
            return DateUtil.getDaysGap(DateUtil.getMillis(
                    DateUtil.getYearOfTime(System.currentTimeMillis()) + 1,
                    DateUtil.getMonthOfTime(anniversaryBean.getTime()),
                    DateUtil.getDayOfTime(anniversaryBean.getTime())), System.currentTimeMillis());
        }
    }

    @Override
    public int getItemViewType(int position) {
        return cardList.get(position).getType();
    }

    @Override
    public int getItemCount() {
        return cardList.size();
    }

    static class countDownHolder extends RecyclerView.ViewHolder {
        TextView title, leaveDays;

        public countDownHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.tv_count_down_title);
            leaveDays = itemView.findViewById(R.id.tv_count_down_leave_days);
        }
    }

    static class promiseHolder extends RecyclerView.ViewHolder {
        TextView name;

        public promiseHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tv_promise_name);
        }
    }

    static class anniversaryHolder extends RecyclerView.ViewHolder {
        TextView title, time, leaveTime;

        public anniversaryHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.tv_anniversary_title);
            time = itemView.findViewById(R.id.tv_anniversary_time);
            leaveTime = itemView.findViewById(R.id.tv_anniversary_leave_time);
        }
    }

    static class todoListHolder extends RecyclerView.ViewHolder {
        TextView title, time;
        LinearLayout ll;
        ImageView addTodo;

        public todoListHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.tv_todo_list_title);
            time = itemView.findViewById(R.id.tv_todo_list_start_time);
            ll = itemView.findViewById(R.id.ll_todo_list_time_line);
            addTodo = itemView.findViewById(R.id.iv_todo_list_add_todo);
        }
    }

    public interface OnClickAddTodoListener{
        void onClickAddTodo(TodoBsdFragment todoBsdFragment, long todoListTime);
    }

    public void setOnClickAddTodoListener(OnClickAddTodoListener onClickAddTodoListener) {
        this.onClickAddTodoListener = onClickAddTodoListener;
    }
}
